﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using suirui.ZhuMu.Common;
using suirui.ZhuMu.Log;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace suirui.ZhuMu.WebCore
{
    public class CustomActionFilterAttribute : Attribute, IActionFilter
    {
        public async void OnActionExecuted(ActionExecutedContext context)
        {
            await Task.Run(() =>
            {
                //判断是否开启操作日志并跟踪记录
                var openLog = AppConfigration.Configuration["OpenOperateTrackLog"] ?? "false";
                if (string.IsNullOrWhiteSpace(openLog)) return;
                if (!bool.Parse(openLog)) return;

                var result = context.Result;
                ObjectResult objectResult = result as ObjectResult;
                var newLine = Environment.NewLine;
                var stringBuilder = new StringBuilder();
                //stringBuilder.Append($"==================Begin==================").Append(newLine);
                stringBuilder.Append($"操作类型:OnActionExecuted").Append(newLine);
                stringBuilder.Append($"结束时间:{DateTime.Now}").Append(newLine);
                stringBuilder.Append($"调用Controller:{context.RouteData.Values["controller"]}").Append(newLine);
                stringBuilder.Append($"调用Action:{context.RouteData.Values["action"]}").Append(newLine);
                stringBuilder.Append($"调用者:{AppConfigration.Configuration["LoginName"]}").Append(newLine);
                stringBuilder.Append($"执行结果:{Newtonsoft.Json.JsonConvert.SerializeObject(objectResult?.Value, Newtonsoft.Json.Formatting.Indented)}").Append(newLine);
                //stringBuilder.Append("==================End====================").Append(newLine);
                //var resultLog = $"{DateTime.Now} 调用 {context.RouteData.Values["action"]} api 完成；执行结果：{Newtonsoft.Json.JsonConvert.SerializeObject(objectResult.Value)}";
                DefaultLogFactory.Instance.Message_Loger.Info(stringBuilder.ToString());
                DefaultLogFactory.Instance.Message_Loger.Info("============================================================================");
            });
        }

        public async void OnActionExecuting(ActionExecutingContext context)
        {
            //context.HttpContext.Response.Headers["Access-Control-Allow-Origin"] = "*";//解决拦截器添加后跨域不生效的问题
            //if (!context.ModelState.IsValid)//验证参数的合法性问题。返回错误信息
            //{
            //}
            //var claims = context.HttpContext.User.Claims;
            //if (claims?.Count() > 0)
            //{
            //    var roleType = int.Parse(claims?.First(c => c.Type.ToLower().Contains("role")).Value);
            //    //不是管理人员
            //    if (roleType <= 0 || roleType > 4)
            //    {
            //        context.Result = new BadRequestResult();
            //    }
            //}

            await Task.Run(() =>
            {
                //判断是否开启操作日志并跟踪记录
                var openLog = AppConfigration.Configuration["OpenOperateTrackLog"] ?? "false";
                if (string.IsNullOrWhiteSpace(openLog)) return;
                if (!bool.Parse(openLog)) return;

                var newLine = Environment.NewLine;
                var stringBuilder = new StringBuilder();
                //stringBuilder.AppendLine($"==================Begin==================");
                stringBuilder.Append($"操作类型:OnActionExecuting").Append(newLine);
                stringBuilder.Append($"开始时间:{DateTime.Now}").Append(newLine);
                stringBuilder.Append($"调用Controller:{context.RouteData.Values["controller"]}").Append(newLine);
                stringBuilder.Append($"调用Action:{context.RouteData.Values["action"]}").Append(newLine);
                stringBuilder.Append($"调用者:{AppConfigration.Configuration["LoginName"]}").Append(newLine);
                stringBuilder.Append($"执行参数:{Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments, Newtonsoft.Json.Formatting.Indented)}").Append(newLine);
                //stringBuilder.AppendLine("==================End====================");
                //var actionLog = $"{DateTime.Now} 开始调用 {context.RouteData.Values["action"]} api；参数为：{Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments)}";
                DefaultLogFactory.Instance.Message_Loger.Info(stringBuilder.ToString());
                DefaultLogFactory.Instance.Message_Loger.Info("============================================================================");
            });
        }

        ///// <summary>
        ///// 获取IP
        ///// </summary>
        ///// <returns></returns>
        //public string GetIP()
        //{
        //    string ip = string.Empty;
        //    if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
        //        ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
        //    if (string.IsNullOrEmpty(ip))
        //        ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"]);
        //    return ip;
        //}
    }
}
